function getRandom(min,max){
  return Math.floor(Math.random() * (max + 1 - min) + min);
}
class Point{
    constructor(cvs){
        this.r = 2;
        this.x = getRandom(0,cvs.width - this.r /2);
        this.y = getRandom(0,cvs.height - this.r /2);
        this.xSpeed = getRandom(-50,50);
        this.ySpeed = getRandom(-50,50);
        this.lastDrawTime = null;
    }

    draw(cvs,ctx){
        if(this.lastDrawTime){
            const duration = (Date.now() - this.lastDrawTime)/1000;
            const xDis = this.xSpeed * duration ;
            const yDis = this.ySpeed * duration;
            let x = this.x + xDis;
            let y = this.y + yDis;
            if(x>cvs.width - this.r / 2){
                x = cvs.width - this.r /2;
                this.xSpeed = -this.xSpeed;
            }else if(x < 0){
                x = 0;
                this.xSpeed = - this.xSpeed;
            }
            if(y>cvs.height - this.r / 2){
                y = cvs.height - this.r /2;
                this.ySpeed = -this.ySpeed;
            }else if(y < 0){
                y = 0;
                this.ySpeed = - this.ySpeed;
            }
            this.x = x;
            this.y = y;
        }
        ctx.beginPath();
        ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
        ctx.fillStyle  = '#ceaf00';
        ctx.fill();
        this.lastDrawTime = Date.now();
    }
}
class Graph{
    constructor(cvs,pointNum = 50,maxDis = 300){
        this.cvs = cvs;
        this.ctx = cvs.getContext('2d');
        this.maxDis = maxDis;
        this.points = new Array(pointNum).fill(0).map(()=>new Point(cvs));
    }
    draw(){
        requestAnimationFrame(()=>{
            this.draw();
        })
        this.ctx.clearRect(0, 0, this.cvs.width, this.cvs.height);
        for(let i = 0; i < this.points.length;i++){
            const p1 = this.points[i];
            p1.draw(this.cvs,this.ctx);
            for(let j = i+1;j < this.points.length;j++){
                const p2 = this.points[j];
                const d = Math.sqrt((p1.x - p2.x)** 2 + (p1.y - p2.y)**2);
                if(d > this.maxDis){
                    continue;
                }
                    this.ctx.beginPath();
                    this.ctx.moveTo(p1.x,p1.y);
                    this.ctx.lineTo(p2.x,p2.y);
                    this.ctx.closePath();
                    this.ctx.strokeStyle  = `rgba(182,155,00,${1-d/this.maxDis})`;
                    this.ctx.stroke();
            }
        }

    }
}
// const cvs = document.querySelector('canvas');
// const ctx = cvs.getContext('2d');


export default Graph;